package de.pelizaeus.app;



import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import de.pelizaeus.app.other.Lehrer;
import de.pelizaeus.app.other.Utils;


public class LehrerFragment extends Fragment {

    protected ArrayList<Lehrer> lehrerList = new ArrayList<Lehrer>();

    private ListView listViewSearch;
    private EditText editSearchView;
    private final Context context = getActivity();

    private SearchAdapter adapter;
    private ArrayList<Lehrer> sortedItems = new ArrayList<Lehrer>();
    private ArrayList<Lehrer> OrignalItems;

    public LehrerFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_lehrer, container, false);
        listViewSearch = (ListView) rootView.findViewById(R.id.LehrerListView);
        editSearchView = (EditText) rootView.findViewById(R.id.editText);




        if (!Utils.isOnline(getActivity()))
        {
            Toast.makeText(getActivity(), "Es ist ein Verbindungsfehler aufgetreten!", Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }
        else {
            new Parser().execute();
        }
        return rootView;
    }

    private class Parser extends AsyncTask<Void,Void,Void>
    {
        String string = "";
        String url = "http://pelizaeus.lspb.de/typo3/ueber-uns/unser-kollegium/";

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            getActivity().setProgressBarIndeterminate(true);
            getActivity().setProgressBarIndeterminateVisibility(true);
            getActivity().setTitle("Wird geladen...");
            editSearchView.setVisibility(View.INVISIBLE);
            listViewSearch.setVisibility(View.INVISIBLE);
        }
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                Document doc = Jsoup.connect(url).get();
                Elements tabelle = doc.select(".contenttable");
                Elements zeilen = tabelle.select("tr");
                String nachname;
                String vorname;
                String kuerzel;
                String fach1;
                String fach2;
                String fach3;
                String sprechzeiten;


                for (Element zeile : zeilen) {
                    if (!zeile.child(0).text().equalsIgnoreCase("Name")) {
                        nachname = zeile.child(0).text();

                        vorname = zeile.child(1).text();
                        kuerzel = zeile.child(2).text();
                        fach1 = zeile.child(3).text();
                        fach2 = zeile.child(4).text();
                        fach3 = zeile.child(5).text();
                        sprechzeiten = zeile.child(6).text();
                        Lehrer lehrer = new Lehrer();
                        lehrer.setVorname(vorname);
                        lehrer.setName(nachname);
                        String faecher = fach1 + " " + fach2 + " " + fach3;
                        lehrer.setFaecher(faecher);
                        lehrer.setKuerzel(kuerzel);
                        lehrerList.add(lehrer);
                        System.out.println(nachname + " " + vorname + " " + kuerzel + " " + fach1 + " " + fach2 + " " + fach3 + " " + sprechzeiten);
                    }
                }
            }
            catch (final Exception e)
            {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(context, "Es ist ein Verbindungsfehler aufgetreten!", Toast.LENGTH_SHORT).show();

                        e.printStackTrace();
                        getActivity().finish();
                    }
                });
                return null;
            }
            return null;
        }

        protected void onPostExecute(Void result)
        {
            // ((TextView) getActivity().findViewById(R.id.textView)).setText(string);

            OrignalItems = lehrerList;
            sortedItems.addAll(OrignalItems);


            adapter = new SearchAdapter(getActivity(), sortedItems);
            listViewSearch.setAdapter(adapter);
            editSearchView.addTextChangedListener(searchTxtChangeListener);


            getActivity().setProgressBarIndeterminateVisibility(false);
            getActivity().setTitle(R.string.activity_name_lehrer);
            editSearchView.setVisibility(View.VISIBLE);
            listViewSearch.setVisibility(View.VISIBLE);
        }

    }TextWatcher searchTxtChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            int textlength = editSearchView.getText().length();
            sortedItems.clear();

            for (Lehrer OrignalItem : OrignalItems) {
                if (textlength <= OrignalItem.getName().length()) {
                    if (editSearchView
                            .getText()
                            .toString()
                            .equalsIgnoreCase(
                                    (String) OrignalItem.getName().subSequence(0,
                                            textlength)
                            )) {
                        sortedItems.add(OrignalItem);

                    }
                }
            }

            adapter.notifyDataSetChanged();


        }
    };


    class SearchAdapter extends BaseAdapter {
        Context context;
        ArrayList<Lehrer> list;


        private LayoutInflater inflater = null;

        public SearchAdapter(Context context, ArrayList<Lehrer> list) {
            this.context = context;
            this.list = list;

            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            ViewHolder holder;
            if (vi == null) {
                vi = inflater.inflate(R.layout.lehrerlist_item, null);
                holder = new ViewHolder();
                holder.txtName = (TextView) vi.findViewById(R.id.name);
                holder.txtKuerzel = (TextView) vi.findViewById(R.id.kuerzel);
                holder.txtFaecher = (TextView) vi.findViewById(R.id.faecher);
                // holder.layoutRelative = (RelativeLayout) vi.findViewById(R.id.LehrerListView);

                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }

            if (list.get(position).getName().equalsIgnoreCase("Referendare:")) {
                holder.txtName.setText(list.get(position).getName());
                holder.txtKuerzel.setText("");
                holder.txtFaecher.setText("");
            }
            else
            {
                holder.txtName.setText(list.get(position).getName() + ", " + list.get(position).getVorname() );
                holder.txtKuerzel.setText(list.get(position).getKuerzel());
                holder.txtFaecher.setText(list.get(position).getFaecher());
            }

            return vi;
        }

        class ViewHolder {
            RelativeLayout layoutRelative;
            TextView txtName;
            TextView txtKuerzel;
            TextView txtFaecher;


        }
    }

}
